package tech.dx.springdb.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.dx.springdb.entity.User;
import tech.dx.springdb.respository.UserRepository;
import tech.dx.springdb.service.UserService;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Override
    public List<User> getUserList() {
        List<User> all = userRepository.findAll();
        return all;
    }

    @Override
    public Optional<User> getUserByEmail(@NotEmpty @Email String email) {
        Optional<User> userByEmail = userRepository.findUserByEmail(email);
        return userByEmail;
    }

    @Override
    public User addUser(@NotEmpty User user) {
        @NotEmpty User save = userRepository.save(user);
        return save;
    }

    @Override
    public User updateUserById(@NotEmpty User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteUserById(int Id) {
        userRepository.deleteUserById( Id);
    }

    @Override
    public Page<User> getPageUserList(int page, int pageCount) {
        Sort createTime = new Sort(Sort.Direction.ASC, "createTime");
        PageRequest pageRequest =  PageRequest.of(page, pageCount, createTime);
        return userRepository.findAll(pageRequest);
    }

    @Override
    public Optional<User> getById(long id) {
        Optional<User> byId = userRepository.findById(id);
        return byId;
    }
}
